package org.genntii.smopenid.controller;


import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.genntii.smopenid.client.SteamPlayerClient;
import org.genntii.smopenid.dto.SteamOpenIdLoginDTO;
import org.genntii.smopenid.client.UserClient;
import org.genntii.smopenid.service.SteamService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@RestController
@RequestMapping("/steam")
public class SteamController {

    @Resource
    private SteamService service;

    @Resource
    private UserClient userClient;

    @Resource
    private SteamPlayerClient steamPlayerClient;

    @GetMapping("/login/{userId}")
    public ModelAndView login(@PathVariable Long userId){
        return new ModelAndView("steam", service.getOpenIdAttributes(userId));
    }

    @GetMapping("/login/redirect/{userId}")
    public ModelAndView loginRedirect(@PathVariable Long userId,
                                      @RequestParam Map<String, String> allRequestParam, Model model){
        System.out.println(allRequestParam);
        SteamOpenIdLoginDTO dto = SteamOpenIdLoginDTO.builder()
                .ns(allRequestParam.get("openid_ns"))
                .op_endpoint(allRequestParam.get("openid.op_endpoint"))
                .claimed_id(allRequestParam.get("openid.claimed_id"))
                .identity(allRequestParam.get("openid.identity"))
                .return_to(allRequestParam.get("openid.return_to"))
                .response_nonce(allRequestParam.get("openid.response_nonce"))
                .assoc_handle(allRequestParam.get("openid.assoc_handle"))
                .signed(allRequestParam.get("openid.signed"))
                .sig(allRequestParam.get("openid.sig"))
                .build();

        //截取字符串获得steamId
        String[] parts = dto.getIdentity().split("/");
        String steamId = parts[parts.length - 1];
        System.out.println(steamId);
        System.out.println(userId);

        userClient.openId(Long.valueOf(steamId),userId);
//        steamPlayerClient.getSteamPlayerBySteamid(steamId);

        service.sendMQ(steamId);
        model.addAttribute("userId", userId);

        return new ModelAndView("originalPage",service.getOriginalPageAttributes());

    }

}
